<?php

class asynchronous_MessageController extends Zend_Controller_Action {

	function init() {
		header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
		header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
		$this->getHelper('viewRenderer')->setNoRender();
	}

	//Put a new message into the asynchronous queue for processing
	function putAction() {

	} //end putaction

	//Process the next message in the queue (usually called by outside like front end or daemon job)
	function processAction() {

		Zend_Registry::get('dt_log')->log('asynchronous message processing called',Zend_Log::INFO);
		//We retrieve the queue
		$queue = Zend_Registry::get('dt_asynchronousQueue');
		$messages = $queue->receive(1);
		//Messages are prioritary, if no message we check the cron processes
		if(count($messages) > 0) {		
			foreach($messages as $i => $message) {
				Zend_Registry::get('dt_log')->log('adding asynchronous message to the stack:'.$message->getModule().'-'.$message->getController().'-'.$message->getAction(),Zend_Log::INFO);
				$this->_helper->actionStack($message->getAction(), $message->getController(),$message->getModule(), $message->getParams());
				$queue->deleteMessage($message);
			}//end foreach
		return;
		} //end count(message) > 0
		

		Zend_Registry::get('dt_log')->log('No asynchronous message to proceed, checking cron queues',Zend_Log::INFO);
		
		require_once('asynchronous/objects/cronjobRun.php');
		$jobRunObject = asynchronous_Object_CronjobRun::getJobToRun();
		if(empty($jobRunObject)) {
			Zend_Registry::get('dt_log')->log('No cron job to process',Zend_Log::INFO);				
			return;
		}		
		
		Zend_Registry::get('dt_log')->log('cron job to run :'.serialize($jobRunObject),Zend_Log::NOTICE);				
		$job = $jobRunObject->getJobObject();
		
		Zend_Registry::get('dt_log')->log('adding cron message to the stack:'.$job->getModule().'-'.$job->getController().'-'.$job->getAction(),Zend_Log::INFO);
		$this->_helper->actionStack($job->getAction(), $job->getController(),$job->getModule(), array());
		$jobRunObject->markJobAsRan();

		//We warn that the message need sto be logged in the cronjobs database
		//Used in asynchronous front end plugin
		$this->_setParam('draftrack_cronjobId', $jobRunObject->getRunId());

		
		
	} //end processaction
  
} //End class
